//
//  HCAnimationGroupView.m
//  HCAnimationGroupView
//
//  Created by 王恕 on 16/3/4.
//  Copyright © 2016年 王恕. All rights reserved.
//

#import "HCAnimationGroupView.h"

@interface HCAnimationGroupView ()

@property (weak, nonatomic) IBOutlet UIImageView *birdImageView;
@property (weak, nonatomic) IBOutlet UIButton *controlButton;


@end

@implementation HCAnimationGroupView


+(instancetype) animationGroupView{
    HCAnimationGroupView *view = [[[NSBundle mainBundle] loadNibNamed:@"HCAnimationGroupView" owner:self options:nil] lastObject];
    return view;
}


- (IBAction)clickBtn:(UIButton *)btn {
    if (btn.selected == NO) {
        //播放动画
        [self playAnimation];
        //修改按钮状态
        btn.selected = YES;
    }else if (btn.selected == YES) {
        //暂停播放
        [self pauseAnimation];
        //修改按钮状态
        btn.selected = NO;
    }
}

-(void) playAnimation{
    
    //根据layer.speed的值来处理 开始--暂停--继续 逻辑
    if (self.birdImageView.layer.speed == 1.0) {
        [self beginAnimation];
        
    }
    else if (self.birdImageView.layer.speed == 0.0){
        [self resumeAnimation];
    }
    
}

/*开始播放*/
-(void) beginAnimation{
    /*动画1设置*/
    CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animation];
    animation1.keyPath = @"position";
    //获取初始position
    CGPoint originalPosition = self.birdImageView.layer.position;
    CGFloat originalX = originalPosition.x;
    CGFloat originalY = originalPosition.y;
    NSValue *animation1Value1 = [NSValue valueWithCGPoint:CGPointMake(originalX + 80, originalY)];
    NSValue *animation1Value2 = [NSValue valueWithCGPoint:originalPosition];
    animation1.values = @[animation1Value2, animation1Value1, animation1Value2];
    
    /*动画2设置*/
    CAKeyframeAnimation *animation2 = [CAKeyframeAnimation animation];
    animation2.keyPath = @"transform.scale";
    animation2.values = @[@(1.0),@(2.0),@(1.0)];
    
    /*动画3设置*/
    CAKeyframeAnimation *animation3 = [CAKeyframeAnimation animation];
    animation3.keyPath = @"opacity";
    animation3.values = @[@(1.0),@(0.2),@(1.0)];
    
    /*设置动画组*/
    CAAnimationGroup *animationGroup = [CAAnimationGroup animation];
    animationGroup.animations = @[animation1,animation2,animation3];
    animationGroup.duration = 2.0;
    animationGroup.repeatCount = MAXFLOAT;
    
    [self.birdImageView.layer addAnimation:animationGroup forKey:nil];
}

/*暂停播放*/
-(void) pauseAnimation{
    CALayer *layer = self.birdImageView.layer;
    
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
    
}

/*继续播放*/
-(void) resumeAnimation{
    CALayer *layer = self.birdImageView.layer;
    
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}



@end
